package com.neihe.config;

import cn.hutool.core.util.StrUtil;
import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.neihe.common.base.ApiException;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

/**
 * OSS文件存储引擎配置类
 */
@Component
@Data
@ConfigurationProperties(prefix = "aliyun.oss")
public class OssConfig {

    private String callbackUrl;

    private String endpoint;

    private String accessKeyId;

    private String accessKeySecret;

    private String bucketName;

    /**
     * 注入OSS操作客户端对象
     */
    @Bean(destroyMethod = "shutdown")
    public OSS ossClient() {
        if (StrUtil.isBlank(getEndpoint()) && StrUtil.isBlank(getAccessKeyId()) &&
                StrUtil.isBlank(getAccessKeySecret()) && StrUtil.isBlank(getBucketName())) {
            throw new ApiException("OSS缺少关键配置！");
        }
        ClientBuilderConfiguration conf = new ClientBuilderConfiguration();
        // 设置证书验证
        conf.setSupportCname(true);
        // 使用默认的证书验证
        conf.setVerifySSLEnable(true);
        // 如果需要信任所有证书(不推荐在生产环境使用)
        conf.setVerifySSLEnable(false);
        return new OSSClientBuilder().build(getEndpoint(), getAccessKeyId(), getAccessKeySecret(), conf);
    }
}
